package com.chii.color.service.impl;

import com.chii.color.mapper.FlowIndicatorMapper;
import com.chii.color.mapper.IpStatisticsMapper;
import com.chii.color.po.FlowIndicator;
import com.chii.color.po.IpStatistics;
import com.chii.color.service.StatisticsService;
import com.chii.color.utils.RedisUtil;
import org.bouncycastle.util.IPAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private IpStatisticsMapper ipStatisticsMapper;
    @Autowired
    private FlowIndicatorMapper flowIndicatorMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public FlowIndicator getFlowIndicator() {
        return flowIndicatorMapper.selectByPrimaryKey(1);
    }


    @Override
    public int addIpCount(String ip) {
        IpStatistics ipStatistics = ipStatisticsMapper.selectByIp(ip);
        //第一次记录该ip
        if (ipStatistics == null) {
            synchronized (ip.intern()) {
                ipStatistics = new IpStatistics();
                ipStatistics.setCount(1L);
                ipStatistics.setIp(ip);
                ipStatistics.setCreatedAt(new Date());
                ipStatisticsMapper.insert(ipStatistics);
            }
            flowIndicatorMapper.updateCount();
        } else {
            ipStatisticsMapper.updateCount(ipStatistics.getId());
            flowIndicatorMapper.updateCountNoUv();
        }
        return 0;

    }

    @PostConstruct
    private void initRedis() {
        if (!redisUtil.hasKey("pv")) {
            redisUtil.set("pv", 0);
        }
        if (!redisUtil.hasKey("uv")) {
            redisUtil.set("uv", 0);
        }
        if (!redisUtil.hasKey("vv")) {
            redisUtil.set("vv", 0);
        }
    }

    @Override
    public int addIpByRedis(String ip) {
        boolean ipv4 = IPAddress.isValidIPv4(ip);
        double count;
        if (ipv4) {
            count = redisUtil.hincr("ipv4", ip, 1);
        } else {
            count = redisUtil.hincr("ipv6", ip, 1);
        }
        if (count == 1) {
            redisUtil.incr("uv", 1);
            redisUtil.incr("pv", 1);
            redisUtil.incr("vv", 1);
        } else {
            redisUtil.incr("uv", 1);
            redisUtil.incr("vv", 1);
        }

        return 0;
    }


}
